package com.netease.nim.avchatkit.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.media.AudioManager;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.AVChatUserData;
import com.netease.nim.avchatkit.R;
import com.netease.nim.avchatkit.activity.AVChatActivity;
import com.netease.nim.avchatkit.common.imageview.HeadImageView;
import com.netease.nim.avchatkit.common.permission.BaseMPermission;
import com.netease.nim.avchatkit.common.util.ScreenUtil;
import com.netease.nim.avchatkit.common.widgets.ToggleListener;
import com.netease.nim.avchatkit.common.widgets.ToggleState;
import com.netease.nim.avchatkit.common.widgets.ToggleView;
import com.netease.nim.avchatkit.constant.AVChatExitCode;
import com.netease.nim.avchatkit.controll.AVChatController;
import com.netease.nim.avchatkit.module.AVChatControllerCallback;
import com.netease.nim.avchatkit.module.AVSwitchListener;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoScalingType;
import com.netease.nimlib.sdk.avchat.model.AVChatCameraCapturer;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.netease.nimlib.sdk.avchat.model.AVChatSurfaceViewRenderer;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import lumingweihua.future.cn.baselibgxh.adapter.BaseViewHolder;
import lumingweihua.future.cn.baselibgxh.adapter.CommonAdapter;
import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.FutureApi;
import lumingweihua.future.cn.baselibgxh.base.GiftFragment;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.dialog.ChoiseType;
import lumingweihua.future.cn.baselibgxh.domain.TagData;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.PureListRequest;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.ImageUtils;
import lumingweihua.future.cn.baselibgxh.utils.MD5;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;
import lumingweihua.future.cn.baselibgxh.widget.EvalutionTagView;
import lumingweihua.future.cn.baselibgxh.widget.FooterListViewUtil;

/**
 * 视频界面变化及点击事件
 * Created by winnie on 2017/12/11.
 */

public class AVChatVideoUI implements View.OnClickListener, ToggleListener,AbstractRequest.ApiCallBack {

    // constant
    private static final int PEER_CLOSE_CAMERA = 0;
    private static final int LOCAL_CLOSE_CAMERA = 1;
    private static final int AUDIO_TO_VIDEO_WAIT = 2;
    private static final int TOUCH_SLOP = 10;
    private static final String TAG = AVChatVideoUI.class.getSimpleName();

    private final String[] BASIC_PERMISSIONS = new String[]{Manifest.permission.CAMERA,};

    /**
     * surface view
     */
    private LinearLayout largeSizePreviewLayout;
    private FrameLayout smallSizePreviewFrameLayout;
    private LinearLayout smallSizePreviewLayout;
    private ImageView smallSizePreviewCoverImg;//stands for peer or local close camera
    private View largeSizePreviewCoverLayout;//stands for peer or local close camera
    private View touchLayout;

    /**
     * video view
     */
    //顶部控制按钮
    private View topRoot;
//    private View switchAudio;
    private Chronometer time;
    private TextView netUnstableTV;
    //中间控制按钮
    private View middleRoot;
//    private HeadImageView headImg;
//    private TextView nickNameTV;
    private TextView notifyTV;
    private View refuse_receive;
    private TextView refuseTV;
    private TextView receiveTV;
    //底部控制按钮
    private View bottomRoot;
    ToggleView switchCameraToggle;
    ToggleView closeCameraToggle;
    ToggleView muteToggle;
    ImageView recordToggle;
    ImageView hangUpImg;
    private ChoiseType choiseType;
    //face unity
    public View faceUnityRoot;
    //摄像头权限提示显示
    private View permissionRoot;
    //record
    private View recordView;
    private View recordTip;
    private View recordWarning;

    //修改的view
    private ImageView headImg;
    private TextView nickNameTV;
    private TextView tv_chat_limit_time;//限制时间
    private TextView tv_cost;//费用
    private TextView tv_degree;//等级
    private ImageView iv_hang_up;//挂断
    private ImageView iv_receive;//接听
    private ImageView iv_renzheng;//认证图标
    private View tv_tip;//提示
    private View ll_charge;//免费提示
    private TextView tv_charge_time;//免费时间
    private ImageView avchat_liwu;//礼物
    private ImageView avchat_charge;//礼物
    private TextView tv_charge;
    private View rl_close_sxt;
    private View gift_dialog;

    //render
    private AVChatSurfaceViewRenderer smallRender;
    private AVChatSurfaceViewRenderer largeRender;

    // state
    private boolean surfaceInit = false;
    private boolean videoInit = false;
    private boolean shouldEnableToggle = false;
    public boolean canSwitchCamera = false;
    private boolean isInSwitch = false;
    private boolean isPeerVideoOff = false;
    private boolean isLocalVideoOff = false;
    private boolean localPreviewInSmallSize = true;
    private boolean isRecordWarning = false;

    // data
    private TouchZoneCallback touchZoneCallback;
    public AVChatData avChatData;
    private AVChatUserData avChatUserData;
    private String account;
//    private String displayName;

    private int topRootHeight = 0;
    private int bottomRootHeight = 0;

    private String largeAccount; // 显示在大图像的用户id
    private String smallAccount; // 显示在小图像的用户id

    // move
    private int lastX, lastY;
    private int inX, inY;
    private Rect paddingRect;

    private Activity context;
    private View root;
    private View probar;
    private AVChatController avChatController;
    private AVSwitchListener avSwitchListener;

    // touch zone
    public interface TouchZoneCallback {
        void onTouch();
    }

    public AVChatVideoUI(Activity context, View root, AVChatData avChatData, String displayName,
                         AVChatController avChatController, TouchZoneCallback touchZoneCallback,
                         AVSwitchListener avSwitchListener) {
        this.context = context;
        this.root = root;
        this.avChatData = avChatData;
        this.avChatController = avChatController;
        this.touchZoneCallback = touchZoneCallback;
        this.avSwitchListener = avSwitchListener;
        this.smallRender = new AVChatSurfaceViewRenderer(context);
        this.largeRender = new AVChatSurfaceViewRenderer(context);
    }

    /**
     * ********************** surface 初始化 **********************
     */
    View surfaceView;
    TextView tv_close_preview;
    private void findSurfaceView() {
        if (surfaceInit)
            return;
        surfaceView = root.findViewById(R.id.avchat_surface_layout);
        if (surfaceView != null) {
            touchLayout = surfaceView.findViewById(R.id.touch_zone);
            touchLayout.setOnTouchListener(touchListener);

            smallSizePreviewFrameLayout = (FrameLayout) surfaceView.findViewById(R.id.small_size_preview_layout);
            smallSizePreviewLayout = (LinearLayout) surfaceView.findViewById(R.id.small_size_preview);
            smallSizePreviewCoverImg = (ImageView) surfaceView.findViewById(R.id.smallSizePreviewCoverImg);
            tv_close_preview = (TextView) surfaceView.findViewById(R.id.tv_close_preview);
            smallSizePreviewFrameLayout.setOnTouchListener(smallPreviewTouchListener);

            largeSizePreviewLayout = (LinearLayout) surfaceView.findViewById(R.id.large_size_preview);
            largeSizePreviewCoverLayout = surfaceView.findViewById(R.id.notificationLayout);
            rl_close_sxt = surfaceView.findViewById(R.id.rl_close_sxt);

            surfaceInit = true;
        }
    }


    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP && touchZoneCallback != null) {
                touchZoneCallback.onTouch();
            }

            return true;
        }
    };

    private View.OnTouchListener smallPreviewTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(final View v, MotionEvent event) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = x;
                    lastY = y;
                    int[] p = new int[2];
                    smallSizePreviewFrameLayout.getLocationOnScreen(p);
                    inX = x - p[0];
                    inY = y - p[1];

                    break;
                case MotionEvent.ACTION_MOVE:
                    final int diff = Math.max(Math.abs(lastX - x), Math.abs(lastY - y));
                    if (diff < TOUCH_SLOP)
                        break;

                    if (paddingRect == null) {
                        paddingRect = new Rect(ScreenUtil.dip2px(10), ScreenUtil.dip2px(20), ScreenUtil.dip2px(10),
                                ScreenUtil.dip2px(70));
                    }

                    int destX, destY;
                    if (x - inX <= paddingRect.left) {
                        destX = paddingRect.left;
                    } else if (x - inX + v.getWidth() >= ScreenUtil.screenWidth - paddingRect.right) {
                        destX = ScreenUtil.screenWidth - v.getWidth() - paddingRect.right;
                    } else {
                        destX = x - inX;
                    }

                    if (y - inY <= paddingRect.top) {
                        destY = paddingRect.top;
                    } else if (y - inY + v.getHeight() >= ScreenUtil.screenHeight - paddingRect.bottom) {
                        destY = ScreenUtil.screenHeight - v.getHeight() - paddingRect.bottom;
                    } else {
                        destY = y - inY;
                    }

                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) v.getLayoutParams();
                    params.gravity = Gravity.NO_GRAVITY;
                    params.leftMargin = destX;
                    params.topMargin = destY;
                    v.setLayoutParams(params);

                    break;
                case MotionEvent.ACTION_UP:
                    if (Math.max(Math.abs(lastX - x), Math.abs(lastY - y)) <= 5) {
                        if (largeAccount == null || smallAccount == null) {
                            return true;
                        }
                        String temp;
                        switchRender(smallAccount, largeAccount);
                        temp = largeAccount;
                        largeAccount = smallAccount;
                        smallAccount = temp;
                        switchAndSetLayout();
                    }

                    break;
            }

            return true;
        }
    };

    // 大小图像显示切换
    private void switchRender(String user1, String user2) {

        //先取消用户的画布
        if (AVChatKit.getAccount().equals(user1)) {
            AVChatManager.getInstance().setupLocalVideoRender(null, false, 0);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(user1, null, false, 0);
        }
        if (AVChatKit.getAccount().equals(user2)) {
            AVChatManager.getInstance().setupLocalVideoRender(null, false, 0);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(user2, null, false, 0);
        }
        //交换画布
        //如果存在多个用户,建议用Map维护account,render关系.
        //目前只有两个用户,并且认为这两个account肯定是对的
        AVChatSurfaceViewRenderer render1;
        AVChatSurfaceViewRenderer render2;
        if (user1.equals(smallAccount)) {
            render1 = largeRender;
            render2 = smallRender;
        } else {
            render1 = smallRender;
            render2 = largeRender;
        }

        //重新设置上画布
        if (user1.equals(AVChatKit.getAccount())) {
            AVChatManager.getInstance().setupLocalVideoRender(render1, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(user1, render1, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        }
        if (user2.equals(AVChatKit.getAccount())) {
            AVChatManager.getInstance().setupLocalVideoRender(render2, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(user2, render2, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        }
    }

    /**
     * ************************** video 初始化 ***********************
     */
    private void findVideoViews() {
        if (videoInit)
            return;
        View videoRoot = root.findViewById(R.id.avchat_video_layout);
        probar = root.findViewById(R.id.probar);
        gift_dialog = videoRoot.findViewById(R.id.gift_dialog);
        topRoot = videoRoot.findViewById(R.id.avchat_video_top_control);
//        switchAudio = topRoot.findViewById(R.id.avchat_video_switch_audio);
//        switchAudio.setOnClickListener(this);
        time = (Chronometer) videoRoot.findViewById(R.id.avchat_video_time);
        netUnstableTV = (TextView) topRoot.findViewById(R.id.avchat_video_netunstable);

        middleRoot = videoRoot.findViewById(R.id.avchat_video_middle_control);
        headImg = middleRoot.findViewById(R.id.avchat_video_head);
        nickNameTV = (TextView) middleRoot.findViewById(R.id.avchat_video_nickname);
        notifyTV = (TextView) middleRoot.findViewById(R.id.avchat_video_notify);

        tv_chat_limit_time = middleRoot.findViewById(R.id.tv_chat_limit_time);
        tv_cost = middleRoot.findViewById(R.id.tv_cost);
        iv_hang_up = middleRoot.findViewById(R.id.iv_hang_up);
        iv_receive = middleRoot.findViewById(R.id.iv_receive);
        iv_renzheng = middleRoot.findViewById(R.id.iv_renzheng);
        tv_degree = middleRoot.findViewById(R.id.tv_degree);
        tv_tip = videoRoot.findViewById(R.id.tv_tip);
        ll_charge = videoRoot.findViewById(R.id.ll_charge);
        tv_charge = videoRoot.findViewById(R.id.tv_charge);
        tv_charge_time = videoRoot.findViewById(R.id.tv_charge_time);
        iv_hang_up.setOnClickListener(this);
        iv_receive.setOnClickListener(this);
        videoRoot.findViewById(R.id.tv_charge).setOnClickListener(this);

        refuse_receive = middleRoot.findViewById(R.id.avchat_video_refuse_receive);
        refuseTV = (TextView) refuse_receive.findViewById(R.id.refuse);
        receiveTV = (TextView) refuse_receive.findViewById(R.id.receive);
        refuseTV.setOnClickListener(this);
        receiveTV.setOnClickListener(this);

        recordView = videoRoot.findViewById(R.id.avchat_record_layout);
        recordTip = recordView.findViewById(R.id.avchat_record_tip);
        recordWarning = recordView.findViewById(R.id.avchat_record_warning);

        bottomRoot = videoRoot.findViewById(R.id.avchat_video_bottom_control);
//        faceUnityRoot = videoRoot.findViewById(R.id.faceunity_control);

        avchat_liwu = bottomRoot.findViewById(R.id.avchat_liwu);
        avchat_charge = bottomRoot.findViewById(R.id.avchat_charge);

        switchCameraToggle = new ToggleView(bottomRoot.findViewById(R.id.avchat_switch_camera), ToggleState.DISABLE, this);
        closeCameraToggle = new ToggleView(bottomRoot.findViewById(R.id.avchat_close_camera), ToggleState.DISABLE, this);
        muteToggle = new ToggleView(bottomRoot.findViewById(R.id.avchat_video_mute), ToggleState.DISABLE, this);
        recordToggle = (ImageView) bottomRoot.findViewById(R.id.avchat_video_record);
        recordToggle.setEnabled(false);
        recordToggle.setOnClickListener(this);
        hangUpImg = (ImageView) videoRoot.findViewById(R.id.avchat_video_logout);
        hangUpImg.setOnClickListener(this);
        bottomRoot.findViewById(R.id.avchat_screenshot).setOnClickListener(this);
        bottomRoot.findViewById(R.id.avchat_liwu).setOnClickListener(this);
        bottomRoot.findViewById(R.id.avchat_charge).setOnClickListener(this);
        bottomRoot.findViewById(R.id.avchat_meiyan).setOnClickListener(this);

        permissionRoot = videoRoot.findViewById(R.id.avchat_video_permission_control);
        videoInit = true;

//        requestTags();
    }

    public void onResume() {
        surfaceViewFixBefore43(smallSizePreviewLayout, largeSizePreviewLayout);
    }

    public void onDestroy() {

        requestCancelCalling();

        if (time != null) {
            time.stop();
        }
        if (sendCodeThread != null) {
            sendCodeThread.cancel();
            sendCodeThread = null;
        }

        if(timeThread!=null){
            timeThread.cancel();
            timeThread = null;
        }
    }

    /**
     * ********************** 视频流程 **********************
     */

    private boolean isIncomingCall;
    public void showIncomingCall(AVChatData avChatData, AVChatUserData avChatUserData) {
        this.avChatUserData = avChatUserData;
        this.account = avChatData.getAccount();
        isIncomingCall = true;
        findSurfaceView();
        findVideoViews();

        showProfile(avChatUserData,true);//对方的详细信息
        showNotify(R.string.avchat_video_call_request);
        setRefuseReceive(false);
        receiveTV.setText(R.string.avchat_pickup);
        setTopRoot(false);
        setMiddleRoot(true);
        setBottomRoot(false);
        setFaceUnityRoot(false);

        iv_hang_up.setVisibility(View.GONE);
        iv_receive.setVisibility(View.VISIBLE);
    }

    public void doOutgoingCall(String account, AVChatUserData avChatUserData) {
        this.avChatUserData = avChatUserData;
        this.account = account;

        findSurfaceView();
        findVideoViews();

        showProfile(avChatUserData,false);//对方的详细信息
        showNotify(R.string.avchat_wait_recieve);
        setRefuseReceive(false);
        shouldEnableToggle = true;
        enableCameraToggle();   //使用音视频预览时这里可以开启切换摄像头按钮
        setTopRoot(false);
        setMiddleRoot(true);
        setBottomRoot(false);
        setFaceUnityRoot(false);

        iv_hang_up.setVisibility(View.VISIBLE);
        iv_receive.setVisibility(View.GONE);

        avChatController.doCalling(account, AVChatType.VIDEO, new AVChatControllerCallback<AVChatData>() {
            @Override
            public void onSuccess(AVChatData data) {
                avChatData = data;
                avChatController.setAvChatData(data);
                List<String> deniedPermissions = BaseMPermission.getDeniedPermissions((Activity) context, BASIC_PERMISSIONS);
                if (deniedPermissions != null && !deniedPermissions.isEmpty()) {
                    showNoneCameraPermissionView(true);
                    return;
                }

                initLargeSurfaceView(AVChatKit.getAccount());
                canSwitchCamera = true;
            }

            @Override
            public void onFailed(int code, String errorMsg) {
                closeSession();
            }

        });
    }

    public void showVideoInitLayout() {
        findSurfaceView();
        findVideoViews();

        isInSwitch = false;
        enableToggle();
        setTime(true);
        setTopRoot(true);
        setMiddleRoot(false);
        setBottomRoot(true);
        setFaceUnityRoot(false);
        showNoneCameraPermissionView(false);
//        if(isIncomingCall)
        requestCalling();

        if(avChatUserData.isDate()){
            //预约接通
            requestDate();
        }
    }

    // 小图像surface view 初始化
    public void initSmallSurfaceView(String account) {
        smallAccount = account;
        smallSizePreviewFrameLayout.setVisibility(View.VISIBLE);

        // 设置画布，加入到自己的布局中，用于呈现视频图像
        // account 要显示视频的用户帐号
        if (AVChatKit.getAccount().equals(account)) {
            AVChatManager.getInstance().setupLocalVideoRender(null, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
            AVChatManager.getInstance().setupLocalVideoRender(smallRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(account, smallRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        }
        addIntoSmallSizePreviewLayout(smallRender);

        smallSizePreviewFrameLayout.bringToFront();
    }

    private void addIntoSmallSizePreviewLayout(SurfaceView surfaceView) {
        smallSizePreviewCoverImg.setVisibility(View.GONE);
        if (surfaceView.getParent() != null) {
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        }
        smallSizePreviewLayout.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(true);
        smallSizePreviewLayout.setVisibility(View.VISIBLE);
    }


    // 大图像surface view 初始化
    public void initLargeSurfaceView(String account) {
        // 设置画布，加入到自己的布局中，用于呈现视频图像
        // account 要显示视频的用户帐号
        largeAccount = account;

        if (AVChatKit.getAccount().equals(account)) {
            AVChatManager.getInstance().setupLocalVideoRender(largeRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(account, largeRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        }
        addIntoLargeSizePreviewLayout(largeRender);
    }

    private void addIntoLargeSizePreviewLayout(SurfaceView surfaceView) {
        if (surfaceView.getParent() != null) {
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        }
        largeSizePreviewLayout.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(false);
        largeSizePreviewCoverLayout.setVisibility(View.GONE);
        rl_close_sxt.setVisibility(View.GONE);
    }

    /**
     * ******************* 音视频切换 *******************
     */

    public void onVideoToAudio() {
        smallSizePreviewFrameLayout.setVisibility(View.INVISIBLE);
    }

    public void onAudioToVideo() {
        findVideoViews();
        findSurfaceView();

        showNotificationLayout(AUDIO_TO_VIDEO_WAIT);

        isInSwitch = true;

        setTime(true);
        setTopRoot(true);
        setMiddleRoot(false);
        setBottomRoot(true);
        setFaceUnityRoot(false);

        showRecordView(avChatController.isRecording(), isRecordWarning);
    }

    public void onAudioToVideoAgree(String largeAccount) {
        showVideoInitLayout();

        muteToggle.toggle(AVChatManager.getInstance().isLocalAudioMuted() ? ToggleState.ON : ToggleState.OFF);
        closeCameraToggle.toggle(ToggleState.OFF);
        switchCameraToggle.off(false);
        recordToggle.setEnabled(true);
        recordToggle.setSelected(avChatController.isRecording());

        //打开视频
        AVChatManager.getInstance().enableVideo();
        AVChatManager.getInstance().startVideoPreview();

        // 是否在发送视频 即摄像头是否开启
        if (AVChatManager.getInstance().isLocalVideoMuted()) {
            AVChatManager.getInstance().muteLocalVideo(false);
            localVideoOn();
        }

        initLargeSurfaceView(largeAccount);
        initSmallSurfaceView(AVChatKit.getAccount());

        showRecordView(avChatController.isRecording(), isRecordWarning);
    }

    /********************** 界面显示 **********************************/

    // 显示个人信息
    private void showProfile(AVChatUserData avChatUserData,boolean isIncomingCall) {
//        headImg.loadBuddyAvatar(account);
//        Picasso.with(context)
//                .load(url)
//                .into(headImg);
        ImageLoader.getInstance().displayImage(avChatUserData.getImage(), headImg);
        nickNameTV.setText(avChatUserData.getNickname());

        if(isIncomingCall)
            tv_cost.setText("对方正在请求视频连线");
        else if(!MyApplication.getInstance().isZhubo && avChatUserData.getFreetime()<=0)
            tv_cost.setText(("每分钟支出"+avChatUserData.getPrice()+"E币"));
        else
            tv_cost.setVisibility(View.GONE);

        if(isIncomingCall){
            //主播等待接听
            iv_renzheng.setVisibility(avChatUserData.getIsauth()?View.VISIBLE:View.GONE);
            tv_degree.setVisibility(View.VISIBLE);
            tv_degree.setText("LV."+avChatUserData.getLevel());
        }else
            tv_chat_limit_time.setVisibility(avChatUserData.getFreetime()>0?View.VISIBLE:View.GONE);
    }

    // 显示通知
    private void showNotify(int resId) {
        notifyTV.setText(resId);
        notifyTV.setVisibility(View.VISIBLE);
    }

    private void setRefuseReceive(boolean visible) {
        refuse_receive.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void setTopRoot(boolean visible) {
        topRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
        if (topRootHeight == 0) {
            Rect rect = new Rect();
            topRoot.getGlobalVisibleRect(rect);
            topRootHeight = rect.bottom;
        }
    }

    private void setMiddleRoot(boolean visible) {
        middleRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void setBottomRoot(boolean visible) {
        bottomRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
        hangUpImg.setVisibility(visible ? View.VISIBLE : View.GONE);
        time.setVisibility(visible ? View.VISIBLE : View.GONE);
        tv_tip.setVisibility(visible ? View.VISIBLE : View.GONE);

        //非主播 显示
        if(!MyApplication.getInstance().isZhubo){
            avchat_liwu.setVisibility(View.VISIBLE);
            avchat_charge.setVisibility(View.VISIBLE);
        }else if(!isIncomingCall && !avChatUserData.isDate()) {// 去电并且不是约会 显示
            avchat_charge.setVisibility(View.VISIBLE);
            avchat_liwu.setVisibility(View.VISIBLE);
        }
        else{//否则不显示
            avchat_liwu.setVisibility(View.GONE);
            avchat_charge.setVisibility(View.GONE);
        }
        if (bottomRootHeight == 0) {
            bottomRootHeight = bottomRoot.getHeight();
        }
    }

    private void setFaceUnityRoot(boolean visible) {
        if (faceUnityRoot == null) {
            return;
        }

        faceUnityRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    // 底部控制开关可用
    private void enableToggle() {
        if (shouldEnableToggle) {
            if (canSwitchCamera && AVChatCameraCapturer.hasMultipleCameras())
                switchCameraToggle.enable();
            closeCameraToggle.enable();
            muteToggle.enable();
            recordToggle.setEnabled(true);
            shouldEnableToggle = false;
        }
    }

    private Timer sendCodeThread;// 验证码计时线�?
    private Timer timeThread;// 计时线�?
    private long countDown = 0;
    private long callTime;
    public long maxTime;
    private int countCallDown = 60;
    private boolean isCountCallDown;

    private void startCount(){

//        doToggleRecord();
        //通话接通，余额判断就应该减去一分钟的单价
        if(avChatUserData.isDate())
            maxTime = avChatUserData.getDateTime();
        else
            maxTime = MyApplication.getInstance().e_money/avChatUserData.getPrice();

        MyApplication.getInstance().e_money = MyApplication.getInstance().e_money - avChatUserData.getPrice();

        if(timeThread == null){
            timeThread = new Timer();
            timeThread.schedule(new TimerTask() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    callTime++;
                    //通话中，每过一分钟余额就减去单价
                    MyApplication.getInstance().e_money = MyApplication.getInstance().e_money - avChatUserData.getPrice();
                    //时间到了
                    if(callTime>=maxTime){
                        timeThread.cancel();
                        timeThread = null;
                        isCountCallDown = true;

                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ll_charge.setVisibility(View.VISIBLE);
//                        tv_charge.setVisibility(View.GONE);
                                handleCheckcode();
                            }
                        });

                    }

                }
            }, 0, 60000);
        }

    }

    private void handleCheckcode() {
        // 发�?�验证码成功
        if (sendCodeThread == null){
            sendCodeThread = new Timer();
            sendCodeThread.schedule(new TimerTask() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    context.runOnUiThread(new Runnable() {
                        public void run() {
                            if(isCountCallDown){
                                if (countCallDown == 0) {
                                    // 计时完成
                                    sendCodeThread.cancel();
                                    sendCodeThread = null;
                                    doHangUp();
//                            bt_check_code.setBackgroundResource(R.drawable.bt_common);

                                } else {
                                    tv_charge_time.setText(getTime(countCallDown) + "S后结束通话");
                                    countCallDown--;
                                }
                            }else{
                                if (countDown == 0) {
                                    // 计时完成
                                    sendCodeThread.cancel();
                                    sendCodeThread = null;
                                    countDown = 60;
                                    doHangUp();
//                            bt_check_code.setBackgroundResource(R.drawable.bt_common);

                                } else {
                                    tv_charge_time.setText(getTime(countDown) + "免费时间结束后正常收费");
                                    countDown--;
                                }
                            }

                        }
                    });
                }
            }, 0, 1000);
        }

    }

    private String getTime(long time){
        if(time<10)
            return "00:0"+time;
        else
            return "00:"+time;
    }


    private void setTime(boolean visible) {
        countDown = avChatUserData.getFreetime();
//        isfree = countDown>0;
        time.setVisibility(visible ? View.VISIBLE : View.GONE);

        if (visible) {
            time.setBase(avChatController.getTimeBase());
            time.start();
            if(!isIncomingCall){
                startCount();
            }
            //充值时间的问题

            if(countDown>0){

                if(countDown>0){
                    String date = SharedPreference.getString(context,"freedate");
                    String dateNowStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                    SharedPreference.saveToSP(context,"freedate",date+","+dateNowStr);
                }

                ll_charge.setVisibility(View.VISIBLE);
                handleCheckcode();
                tv_charge.setVisibility(isIncomingCall?View.GONE:View.VISIBLE);
                tv_charge.setOnClickListener(this);

//                if(!isIncomingCall){
//                    closePreview(!isclose,"免费时间内\n不可开启摄像头");
//                    closeCamera();
//                }
            }else
                isShowEvalution = !MyApplication.getInstance().isZhubo;
        }

    }

    public void showNoneCameraPermissionView(boolean show) {
        permissionRoot.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void enableCameraToggle() {
        if (shouldEnableToggle) {
            if (canSwitchCamera && AVChatCameraCapturer.hasMultipleCameras())
                switchCameraToggle.enable();
        }
    }

    // 摄像头切换时，布局显隐
    private void switchAndSetLayout() {
        localPreviewInSmallSize = !localPreviewInSmallSize;
        largeSizePreviewCoverLayout.setVisibility(View.GONE);
        rl_close_sxt.setVisibility(View.GONE);
        smallSizePreviewCoverImg.setVisibility(View.GONE);
        if (isPeerVideoOff) {
            peerVideoOff();
        }
        if (isLocalVideoOff) {
            localVideoOff();
        }
    }

    /**
     * ******************** 点击事件 **********************
     */

    @Override
    public void toggleOn(View v) {
        onClick(v);
    }

    @Override
    public void toggleOff(View v) {
        onClick(v);
    }

    @Override
    public void toggleDisable(View v) {

    }

    @Override
    public void onClick(View v) {
//        avChatController.toggleSpeaker();
//        OpenSpeaker();
        int i = v.getId();
        if (i == R.id.refuse) {
            doRefuseCall();
        } else if (i == R.id.receive) {
            doReceiveCall();
        }else if (i == R.id.iv_hang_up) {
            doHangUp();
        } else if (i == R.id.iv_receive) {
            doReceiveCall();
        } else if (i == R.id.avchat_video_logout) {
            doHangUp();
        } else if (i == R.id.avchat_video_mute) {
            avChatController.toggleMute();
        } else if (i == R.id.avchat_switch_camera) {
            avChatController.switchCamera();
        } else if (i == R.id.avchat_close_camera) {
            if(MyApplication.getInstance().isZhubo)
                closePreview(!isclose,"已关闭预览");
            else if(countDown<=0)
                closeCamera();
        } else if (i == R.id.avchat_video_record) {
            doToggleRecord();
        } else if(i == R.id.avchat_liwu){
//            AVChatManager.getInstance().sendControlCommand(avChatData.getChatId(), command, null);
            ((AVChatActivity)context).showGifts();
        }else if (i == R.id.avchat_video_switch_audio) {
            if (isInSwitch) {
                Toast.makeText(context, R.string.avchat_in_switch, Toast.LENGTH_SHORT).show();
            } else {
                avChatController.switchVideoToAudio(avSwitchListener);
            }

        }else if(i == R.id.tv_charge){
//            去充值
            MyApplication.getInstance().gotoCharge();
//            doHangUp();
//            context

        }else if(i == R.id.avchat_charge){
//            去充值
            MyApplication.getInstance().gotoCharge();
//            doHangUp();
//            context

        }else if(i == R.id.avchat_screenshot){
//            截图
            AVChatManager.getInstance().takeSnapshot(account);
        }else if(i == R.id.iv_close){
            closeSession();
        }else if(i == R.id.tv_no_love){
            feel = "2";
            bt_ok.setBackgroundColor(Color.parseColor("#6560e2"));
            tv_no_love.setCompoundDrawables(
                    null, CommonUtils.GetDrawable(context, R.drawable.pingjia_chaping_hei),
                    null, null);
            tv_love.setCompoundDrawables(
                    null, CommonUtils.GetDrawable(context, R.drawable.pingjia_haoping),
                    null, null);

            evalutiontagview.setDatas(tagDatasUnLike);
        }else if(i == R.id.tv_love){
            feel = "1";
            bt_ok.setBackgroundColor(Color.parseColor("#6560e2"));
            tv_no_love.setCompoundDrawables(
                    null, CommonUtils.GetDrawable(context, R.drawable.pingjia_chaping),
                    null, null);
            tv_love.setCompoundDrawables(
                    null, CommonUtils.GetDrawable(context, R.drawable.pingjia_haoping_hong),
                    null, null);
            evalutiontagview.setDatas(tagDatasLike);
        }else if(i == R.id.bt_ok){
            //确定
            if(TextUtils.isEmpty(feel)){
                Toast.makeText(context,"请选择对TA的感觉",Toast.LENGTH_SHORT).show();
                return;
            }
            StringBuilder sb = new StringBuilder();//
            if("1".equals(feel)){
                for(TagData td:tagDatasLike){
                    if(td.isSel())
                        sb.append(",").append(td.getId());
                }
            }else{
                for(TagData td:tagDatasUnLike){
                    if(td.isSel())
                        sb.append(",").append(td.getId());
                }
            }

            if(TextUtils.isEmpty(sb)){
                Toast.makeText(context,"请选择对TA的印象",Toast.LENGTH_SHORT).show();
                return;
            }
            requestEvalution(sb.substring(1));
        }else if((i == R.id.tv_report)){
            if(choiseType==null){
                choiseType = new ChoiseType(context,R.style.dialog_sex);
                choiseType.setOnForResultCallBack(new ChoiseType.OnForResultCallBack() {
                    @Override
                    public void onCallBack(String reason) {
                        requestReport(reason);
                    }
                });
            }

            choiseType.show();
        }else if(i == R.id.avchat_meiyan){
            if(faceUnityRoot!=null){
                if(faceUnityRoot.getVisibility() == View.VISIBLE)
                    faceUnityRoot.setVisibility(View.GONE);
                else
                    faceUnityRoot.setVisibility(View.VISIBLE);
            }
        }
    }

    // 拒绝来电
    private void doRefuseCall() {
        avChatController.hangUp(AVChatExitCode.HANGUP);
        closeSession();
    }

    private void doReceiveCall() {
        showNotify(R.string.avchat_connecting);
        shouldEnableToggle = true;

        avChatController.receive(AVChatType.VIDEO, new AVChatControllerCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                canSwitchCamera = true;
            }

            @Override
            public void onFailed(int code, String errorMsg) {
                closeSession();
            }
        });
    }

    public void doHangUp() {

        if(timeThread!=null){
            timeThread.cancel();
            timeThread = null;
        }
        faceUnityRoot.setVisibility(View.GONE);
        avChatController.hangUp(AVChatExitCode.HANGUP);

        if(avChatUserData.getFreetime()>0){
            //免费 直接结束
            closeSession();
        }else if(callTime>0){//接通过之后
            if(isIncomingCall){//接听方
                //来电  非主播  弹出评价
                if(!MyApplication.getInstance().isZhubo)
                    requestTags();
                else //主播端关闭会话
                    closeSession();
            }else if(avChatUserData.isDate()){
                //拨打方 预约 直接关闭
                closeSession();
            }else//拨打方 发起支付 支付成功后 弹出评价
                requestPay();
        }else
            closeSession();
    }

    public void onHangUp() {

        if(timeThread!=null){
            timeThread.cancel();
            timeThread = null;
        }
        faceUnityRoot.setVisibility(View.GONE);

        if(avChatUserData.getFreetime()>0){
            //免费
            closeSession();
        }else if(callTime>0){
            if(isIncomingCall){
                //来电  非主播评价
                if(!MyApplication.getInstance().isZhubo)
                    requestTags();
                else //主播关闭会话
                    closeSession();
            }else if(avChatUserData.isDate()){
                //去电 预约 直接关闭
                closeSession();
            }else//去电 支付
                requestPay();
        }else
            closeSession();

    }

    /**
     * ********************** 开关摄像头 **********************
     */

    private void closeCamera() {
        if (!AVChatManager.getInstance().isLocalVideoMuted()) {
            // 关闭摄像头
            AVChatManager.getInstance().muteLocalVideo(true);
            localVideoOff();
        } else {
            // 打开摄像头
            AVChatManager.getInstance().muteLocalVideo(false);
            localVideoOn();
        }
    }

    private boolean isclose;
    private void closePreview(boolean isclose,String str){
        this.isclose = isclose;
        tv_close_preview.setVisibility(isclose?View.VISIBLE:View.GONE);
        tv_close_preview.setText(str);
//        if(!isIncomingCall)
//            tv_close_preview.setText("免费时间内\n不可开启摄像头");
    }


    // 对方打开了摄像头
    private void localVideoOn() {
        isLocalVideoOff = false;
        if (localPreviewInSmallSize) {
            smallSizePreviewCoverImg.setVisibility(View.GONE);
        } else {
            largeSizePreviewCoverLayout.setVisibility(View.GONE);
            rl_close_sxt.setVisibility(View.GONE);
        }
    }

    // 本地关闭了摄像头
    private void localVideoOff() {
        isLocalVideoOff = true;
        if (localPreviewInSmallSize)
            closeSmallSizePreview();
        else
            showNotificationLayout(LOCAL_CLOSE_CAMERA);
    }

    // 对方关闭了摄像头
    public void peerVideoOff() {
        isPeerVideoOff = true;
        if (localPreviewInSmallSize) { //local preview in small size layout, then peer preview should in large size layout
            showNotificationLayout(PEER_CLOSE_CAMERA);
        } else {  // peer preview in small size layout
            closeSmallSizePreview();
        }
    }

    // 对方打开了摄像头
    public void peerVideoOn() {
        isPeerVideoOff = false;
        if (localPreviewInSmallSize) {
            largeSizePreviewCoverLayout.setVisibility(View.GONE);
            rl_close_sxt.setVisibility(View.GONE);
        } else {
            smallSizePreviewCoverImg.setVisibility(View.GONE);
        }
    }

    // 关闭小窗口
    private void closeSmallSizePreview() {
        smallSizePreviewCoverImg.setVisibility(View.VISIBLE);
    }

    // 界面提示
    private void showNotificationLayout(int closeType) {
        if (largeSizePreviewCoverLayout == null) {
            return;
        }
        TextView textView = (TextView) largeSizePreviewCoverLayout;
        switch (closeType) {
            case PEER_CLOSE_CAMERA:
                textView.setText(R.string.avchat_peer_close_camera);
                rl_close_sxt.setVisibility(View.VISIBLE);
                ImageLoader.getInstance().displayImage(avChatUserData.getImage(), (ImageView) surfaceView.findViewById(R.id.close_head));
                ((TextView)surfaceView.findViewById(R.id.close_nickname)).setText(avChatUserData.getNickname());
                surfaceView.findViewById(R.id.close_renzheng).setVisibility(avChatUserData.getIsauth()?View.VISIBLE:View.GONE);
                ((TextView)surfaceView.findViewById(R.id.close_degree)).setText("LV."+avChatUserData.getLevel());
                break;
            case LOCAL_CLOSE_CAMERA:
                textView.setText(R.string.avchat_local_close_camera);
                largeSizePreviewCoverLayout.setVisibility(View.VISIBLE);
                break;
            case AUDIO_TO_VIDEO_WAIT:
                textView.setText(R.string.avchat_audio_to_video_wait);
                largeSizePreviewCoverLayout.setVisibility(View.VISIBLE);
                break;
            default:
                return;
        }

    }


    /**
     * ******************** 录制 ***************************
     */

    private void doToggleRecord() {
        avChatController.toggleRecord(AVChatType.VIDEO.getValue(), account, new AVChatController.RecordCallback() {
            @Override
            public void onRecordUpdate(boolean isRecording) {
                showRecordView(isRecording, isRecordWarning);
            }
        });
    }

    public void showRecordView(boolean show, boolean warning) {
        if (show) {
            recordToggle.setEnabled(true);
            recordToggle.setSelected(true);
            recordView.setVisibility(View.VISIBLE);
            recordTip.setVisibility(View.VISIBLE);
            if (warning) {
                recordWarning.setVisibility(View.VISIBLE);
            } else {
                recordWarning.setVisibility(View.GONE);
            }
        } else {
            recordToggle.setSelected(false);
            recordView.setVisibility(View.INVISIBLE);
            recordTip.setVisibility(View.INVISIBLE);
            recordWarning.setVisibility(View.GONE);
        }
    }

    public void showRecordWarning() {
        isRecordWarning = true;
        showRecordView(avChatController.isRecording(), isRecordWarning);
    }

    public void resetRecordTip() {
        isRecordWarning = false;
        avChatController.setRecording(false);
        showRecordView(false, isRecordWarning);
    }

    private boolean isShowEvalution;
    private List<TagData> tagDatasLike;
    private List<TagData> tagDatasUnLike;
    private void closeSession() {
        ((Activity) context).finish();
//        if(isShowEvalution)
//            requestTags();
//        else
//            ((Activity) context).finish();
    }

    public AVChatData getAvChatData() {
        return avChatData;
    }

    private void surfaceViewFixBefore43(ViewGroup front, ViewGroup back) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (back.getChildCount() > 0) {
                View child = back.getChildAt(0);
                back.removeView(child);
                back.addView(child);
            }

            if (front.getChildCount() > 0) {
                View child = front.getChildAt(0);
                front.removeView(child);
                front.addView(child);
            }
        }
    }

    /**
     * 支付
     */
    private void requestPay() {
        if(probar != null)
            probar.setVisibility(View.VISIBLE);
        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/user/one_by_one_video", this);

        req.setParam("token", SharedPreference.getString(context,"token"));
        req.setParam("member_id", avChatUserData.getMember_id());
        req.setParam("anchor_id", avChatUserData.getAnchor_id());
        req.setParam("chat_time", callTime+"");

        String e_money = callTime*avChatUserData.getPrice()+"";
        req.setParam("e_money", e_money);

        String key = "9b4aaf?&&##664bdef@c3fc3efa9";
        req.setParam("sign", MD5.Md5(e_money+System.currentTimeMillis()/1000+key).toLowerCase());

        req.setTag(new ReqTag.Builder().build(3));
        FutureApi.getInstance().add(req);
    }

    private void requestTags(){
        if(probar != null)
            probar.setVisibility(View.VISIBLE);
        PureListRequest<TagData, MamaHaoServerError> req = new PureListRequest<>(
                context,
                Request.Method.GET,
                "/home/getReplayTag",
                this,
                TagData.class);

        req.setTag(new ReqTag.Builder().build(1));
        FutureApi.getInstance().add(req);
    }

    private void requestEvalution(String replay_ids){
        if(probar != null)
            probar.setVisibility(View.VISIBLE);
        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/home/addReplay", this);

        req.setParam("uid", SharedPreference.getString(context,"uid"));
        req.setParam("anchor_id", avChatUserData.getAnchor_id());

        req.setParam("feel", feel);
        req.setParam("replay_ids", replay_ids);

        req.setTag(new ReqTag.Builder().build(2));
        FutureApi.getInstance().add(req);
    }

    /**
     * 举报
     */
    private void requestReport(String content) {
        if(probar != null)
            probar.setVisibility(View.VISIBLE);
        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/home/addReport", this);

        req.setParam("uid", avChatUserData.getMember_id());
        req.setParam("anchor_id", avChatUserData.getAnchor_id());
        req.setParam("reason", content);

        req.setTag(new ReqTag.Builder().build(4));
        FutureApi.getInstance().add(req);
    }

    /**
     * 预约成功
     */
    private void requestDate() {

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/user/answer_appointment", this);

        req.setParam("token", SharedPreference.getString(context,"token"));
        req.setParam("appoint_id", avChatUserData.getAppoint_id());

        req.setTag(new ReqTag.Builder().build(5));
        FutureApi.getInstance().add(req);
    }

    /**
     * 接听状态
     */
    private void requestCalling() {

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/send_anchor_status", this);

        req.setParam("member_id", SharedPreference.getString(context,"uid"));
        req.setParam("status", "2");

        req.setTag(new ReqTag.Builder().build(6));
        FutureApi.getInstance().add(req);
    }

    /**
     * 取消接听状态
     */
    private void requestCancelCalling() {

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "/api/send_anchor_status", this);

        req.setParam("member_id", SharedPreference.getString(context,"uid"));
        req.setParam("status", "1");

        req.setTag(new ReqTag.Builder().build(7));
        FutureApi.getInstance().add(req);
    }

    @Override
    public void onApiOnSuccess(ReqTag tag, Object data) {
        if(probar != null)
            probar.setVisibility(View.GONE);
        switch (tag.getReqId()) {
            case 1:
                // 商品列表
                List<TagData> tagDatas = (List<TagData>) data;
                tagDatasLike = new ArrayList<>();
                tagDatasUnLike = new ArrayList<>();
                for(TagData td:tagDatas){
                    if(td.getTag_name().startsWith("c")){
                        td.setTag_name(td.getTag_name().substring(1));
                        tagDatasUnLike.add(td);
                    }
                    else
                        tagDatasLike.add(td);
                }
                //处理数据
                showEvalution();
                break;
            case 2:
                Toast.makeText(context, "评价成功", Toast.LENGTH_SHORT).show();
                closeSession();
                break;
            case 3:
                //支付成功
                requestTags();
                break;
            case 4:
                Toast.makeText(context, "举报成功", Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
        }
    }

    int payTime;
    @Override
    public void onApiFailure(ReqTag tag, MamaHaoServerError error, AbstractRequest.MamaHaoError clientError) {
        if(probar != null)
            probar.setVisibility(View.GONE);
        switch (tag.getReqId()) {
            case 1:
                showEvalution();
                break;
            case 2:
                Toast.makeText(context, "评价失败", Toast.LENGTH_SHORT).show();
                closeSession();
                break;
            case 3:
                //支付成功
                payTime++;
                if(payTime<3)
                    requestPay();
                break;
            case 4:
                Toast.makeText(context, "举报失败", Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
        }
    }

    private TextView tv_no_love;
    private TextView tv_love;
    private String feel;
    private TextView bt_ok;
    private EvalutionTagView evalutiontagview;
    private void showEvalution(){
        gift_dialog.setVisibility(View.VISIBLE);
        gift_dialog.findViewById(R.id.iv_close).setOnClickListener(this);
        tv_no_love = (TextView) gift_dialog.findViewById(R.id.tv_no_love);
        bt_ok = (TextView) gift_dialog.findViewById(R.id.bt_ok);
        tv_love = (TextView) gift_dialog.findViewById(R.id.tv_love);
        tv_no_love.setOnClickListener(this);
        tv_love.setOnClickListener(this);
        bt_ok.setOnClickListener(this);
        gift_dialog.findViewById(R.id.tv_report).setOnClickListener(this);
        ImageLoader.getInstance().displayImage(avChatUserData.getImage(), (ImageView) gift_dialog.findViewById(R.id.iv_evalution_head), ImageUtils.imgOptionsHead);
        ((TextView)gift_dialog.findViewById(R.id.tv_evalution_name)).setText(avChatUserData.getNickname());
        ((TextView)gift_dialog.findViewById(R.id.tv_call_time)).setText("通话："+callTime+"分钟");
        ((TextView)gift_dialog.findViewById(R.id.tv_call_coin)).setText("消费："+(callTime*avChatUserData.getPrice())+"E币");
        ((TextView)gift_dialog.findViewById(R.id.tv_qinmizhi)).setText("本次亲密值："+(callTime*avChatUserData.getPrice()));
        evalutiontagview = gift_dialog.findViewById(R.id.evalutiontagview);
        evalutiontagview.setTotalWidth(CommonUtils.getScreenSize(context)[0]-CommonUtils.dip2px(context,20));

    }

}
